package com.tx.zlm_replay.common;

import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * @author tx
 * @version 1.0
 * @date 2024/3/18 16:00
 * @description: 分页对象
 */

public class Page<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -7829155887307241267L;
    // 数据
    private List<T> data;
    // 当前页
    private Long page = 1l;
    // 每页大小
    private Long count = 10l;
    // 数据总数
    private Long total = 0l;
    // 多少页
    private Long pageTotal = 0l;

    public Page(Long page, Long count) {
        this.page = page;
        this.count = count;
    }
    public Page(Integer page, Integer count) {
        this.page = page.longValue();
        this.count = count.longValue();
    }
    public Page() {
    }

    /**
     * 通过query对象创建page
     * @param pageQuery
     * @return
     */
    public static Page buildPage(PageQuery pageQuery){
        return new Page(pageQuery.getPage(), pageQuery.getCount());
    }
    public List<T> getData() {
        return data;
    }

    public Page<T> setData(List<T> data) {
        this.total = (long) data.size();
        this.updatePageTotal();
        int startPage = page.intValue();
        if((startPage-1)*count>=total){
            startPage = pageTotal.intValue();
            page = pageTotal;
        }
        int start = (startPage-1) * count.intValue();
        int end =startPage*count.intValue();
        if(end>= total){
            end = total.intValue();
        }
        this.data = data.subList(start, end);
        return this;
    }

    public Long getPage() {
        return page;
    }

    public Page<T> setPage(Long page) {
        if(page>0){
            this.page = page;
        }
        return this;
    }

    public Long getCount() {
        return count;
    }

    public Page<T> setCount(Long count) {
        if(count > 0){
            this.count = count;
            updatePageTotal();
        }
        return this;
    }

    public Long getTotal() {
        return total;
    }

    public Page<T> setTotal(Long total) {
        this.total = total;
        updatePageTotal();
        return this;
    }

    public Long getPageTotal() {
        return pageTotal;
    }

    private void updatePageTotal() {
        this.pageTotal = this.total/this.count +1;
    }

    public Page<T> setPageTotal(Long pageTotal) {
        this.pageTotal = pageTotal;
        return this;
    }
}
